package com.fizzkai.p2p.mgrsite.job;

import com.fizzkai.p2p.bussness.domain.BidRequest;
import com.fizzkai.p2p.bussness.service.IBidRequestService;
import com.fizzkai.p2p.core.util.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;

@Component
public class BidRequesetScheduledJob implements ApplicationListener<ContextRefreshedEvent>{
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        queryBidRequestJob();
    }

    @Autowired
    private IBidRequestService bidRequestService;


    // 定义内存中 List
    private ConcurrentLinkedQueue<BidRequest> bidRequestQueue = new ConcurrentLinkedQueue<>();

    // 每隔 一小时查询 最近一小时 需要 发标的 借款对象
    @Scheduled(cron = "0 0 0/1 * * ?")
    public void queryBidRequestJob() {
        System.out.println("-------------------华丽分割线-xxxxx-----xxxxxxxxxxxxxxxxxxxxxxx----------");
        // 查询 最近一个小时 待发布的借款，放入内存中
        List<BidRequest> list = bidRequestService.queryPublishPendingBidInOneHourRequest();
        list.forEach(System.out::println);
        bidRequestQueue.addAll(list);
    }

    // 每隔 一分钟，直接拿到 bidRequestList 聚合，内存中 进行 遍历
    @Scheduled(cron = "0/5 * * * * ?")
    public void changeBidRequestStateJob(){
        Date now = new Date();
        Iterator<BidRequest> iter = bidRequestQueue.iterator();
        while (iter.hasNext()) {
            BidRequest next = iter.next();
            if (now.getTime() - next.getPublishTime().getTime() >= 0) {
                // 已经到时间了
                next.setBidRequestState(Constants.BIDREQUEST_STATE_BIDDING);    // 设置招标中
                bidRequestService.update(next);
                iter.remove();  // 移除元素
            }
        }
    }


//    @Scheduled(cron = "0/5 * * * * ?")
//    public void doWord(){
//        System.out.println("定时器执行");
//    }
}
